// Copyright (c) 2023 Institute of Software, Chinese Academy of Sciences
// Ripple is licensed under Mulan PSL v2.
// You can use this software according to the terms and conditions of the Mulan PSL v2.
// You may obtain a copy of Mulan PSL v2 at:
//          http://license.coscl.org.cn/MulanPSL2
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
// MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
// See the Mulan PSL v2 for more details.

package ripple.common.storage;

import ripple.common.entity.Item;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class TopicService {
    private Storage storage;

    public Storage getStorage() {
        return storage;
    }

    public void setStorage(Storage storage) {
        this.storage = storage;
    }

    public TopicService(Storage storage) {
        this.setStorage(storage);
    }

    public String getTopic(String topic) {
        try {
            Connection connection = this.getStorage().getConnection();
            String sql = "SELECT * FROM [topic] WHERE [topic] = ?;";
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setString(1, topic);
            ResultSet resultSet = statement.executeQuery();
            String storedTopic = null;
            if (resultSet.next()) {
                storedTopic = resultSet.getString("topic");
            }
            resultSet.close();
            return storedTopic;
        } catch (SQLException exception) {
            exception.printStackTrace();
            return null;
        }
    }

    public List<String> getAllTopics() {
        try {
            Connection connection = this.getStorage().getConnection();
            String sql = "SELECT * FROM [topic];";
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(sql);
            List<String> ret = new ArrayList<>();
            while (resultSet.next()) {
                ret.add(resultSet.getString("topic"));
            }
            resultSet.close();
            return ret;
        } catch (SQLException exception) {
            exception.printStackTrace();
            return null;
        }
    }

    public synchronized boolean newTopic(String topic) {
        if (this.getTopic(topic) != null) {
            return false;
        }

        try {
            Connection connection = this.getStorage().getConnection();
            String sql = "INSERT INTO [topic] ([topic]) VALUES (?);";
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setString(1, topic);
            int count = statement.executeUpdate();
            return count == 1;
        } catch (SQLException exception) {
            exception.printStackTrace();
            return false;
        }
    }
}
